<?php

namespace app\common\model;

use think\Exception;
use think\Model;

class Recharge extends Model
{
    // 表名
    protected $name = 'recharge';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
        'pay_time_text',
	    'status_text'
    ];
	
	
	const STATUS_Y = 1;
    const STATUS_W = 0;
    
	public static $statusList = [
		self::STATUS_Y => '充值成功',
		self::STATUS_W => '待支付'
	];
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return isset($list[$value]) ? $list[$value] : '';
	}


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
    public function user(){
    	return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
    }
	
	/**
	 * 充值成功回调检查充值订单
	 * @param $orderNo 充值订单号
	 * @param $outTradeNo 第三方流水号
	 * @param $amount 充值金额
	 * @param $payType 支付方式
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
    public function checkRechargeRow($orderNo, $outTradeNo, $amount, $payType) {
    	$row = $this->where(['order_no' => $orderNo])->find();
    	if(!$row) {
    		$this->error = __('数据不存在');
    		return false;
	    }
	    
	    
	    if($row['status'] != self::STATUS_W){
	    	return true;
	    }
	    
	    $this->startTrans();
	    try {
	    	//更改充值订单状态
		    $res = $this->where(['id' => $row['id']])
			    ->update([
			        'status' => self::STATUS_Y,
				    'pay_time' => time(),
				    'update_time' => time(),
				    'amount' => $amount,
				    'out_trade_no' => $outTradeNo,
				    'pay_type' => $payType,
			    ]);
		
		    if(!$res) {
		    	throw new Exception(__('更改充值订单状态出错'));
		    }
		    
		    $user = User::get($row['user_id']);
		    
		    //添加流水
		    $fundsModel = new FundsRecord();
		    $fundsRes = $fundsModel->addRecord($row['user_id'], $amount, $user['balance'], $fundsModel::ACCOUNT_TYPE_BALANCE, $fundsModel::OPE_TYPE_PLUS, $fundsModel::TYPE_RECHARGE, $row['id']);
		    if(!$fundsRes) {
		    	throw new Exception(__('添加资金流水出错'));
		    }
		    
		    //添加余额
		    $userRes = $user->setInc('balance', $amount);
		    if(!$userRes) {
		    	throw new Exception(__('添加余额出错'));
		    }
		    
	    	
	    	$this->commit();
	    	return true;
	    } catch (Exception $e) {
	    	$this->rollback();
	    	$this->error = $e->getMessage();
	    	return false;
	    }
    }

}
